package vip.xiaomaoxiaoke.idempotent.support;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import vip.xiaomaoxiaoke.idempotent.support.exception.ExecutionException;


/**
 * 简单执行结果序列化
 */
public class SimpleExecutionResultSerializer implements ExecutionResultSerializer{

    /**
     * 正常结果序列化
     * */
    @Override
    public <T> String serializeResult(T data) {
        if (data == null){
            return "";
        }
        return JSON.toJSONString(data);
    }

    /**
     * 正常结果反序列化
     * */



    @Override
    public <T> T deserializeResult(String data, Class<T> cls) {
        if (StringUtils.isEmpty(data)){
            return null;
        }
        return JSON.parseObject(data, cls);
    }

    /**
     * 序列化异常
     * */
    @Override
    public <T extends Exception> String serializeException(T data) {
        if (data == null){
            return "";
        }
        return data.getClass().getName();
    }

    /**
     * 反序列化异常
     * */
    @Override
    public <T extends Exception> T deserializeException(String data) {
        if (StringUtils.isEmpty(data)){
            return (T) new ExecutionException();
        }

        try {
            return (T) Class.forName(data).newInstance();
        }catch (Exception e){
            return (T) new ExecutionException();
        }
    }
}
